<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <link href="js/video-js.css" rel="stylesheet"/>
    <link href="bootstrap/bootstrap.min.css" type="text/css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="bootstrap/bootstrap.min.css" type="text/css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: Arial, sans-serif;
        }

        body {
            background-color: #f0f0f0;
        }

        /* 摄像头信息区 */
        .camera-info {
            padding: 15px;
            background: #fff;
            margin: 10px;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .info-item {
            display: flex;
            gap: 10px;
            align-items: center;
            justify-content: center; /* 让子元素在水平方向上居中 */
            width: 100%; /* 确保 .info-item 占据父元素的全部宽度 */
        }

        /* 视频显示区 */
        .video-section {
            margin: 20px 0;
            position: relative;
        }

        video {
            width: 100%;
            height: auto;
            display: block;
        }

        /* 功能标签栏 */
        .tab-bar {
            display: flex;
            justify-content: space-around; /* 也可以用 space-between */
            margin: 20px 0;
        }

        .tab-item {
            color: #666;
            cursor: pointer;
            flex: 1; /* 平分宽度 */
            text-align: center; /* 文字居中 */
        }

        .tab-item.active {
            color: #000;
            border-bottom: 2px solid #4a90e2;
            padding-bottom: 5px;
        }

        /* 操作按钮区 */
        .action-buttons {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            padding: 0 20px;
        }

        .button {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 5px;
            cursor: pointer;
        }

        .icon {
            width: 50px;
            height: 50px;
            background: #e0e0e0;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden; /* 防止图标溢出 */
        }

        .icon img {
            width: 30px; /* 设置图标宽度 */
            height: 30px; /* 设置图标高度 */
            object-fit: contain; /* 确保图标完整显示 */
        }

        .big-button {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 8px; /* 图标与文字间距 */
            padding: 16px;
            border-radius: 12px;
            background-color: #f0f0f0;
            cursor: pointer;
        }

        .big-icon {
            width: 120px;
            height: 120px;
            background: #e0e0e0;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 24px;
            text-align: center; /* 底部字体居中 */
            overflow: hidden; /* 防止图标溢出 */
        }

        .big-icon img {
            width: 60px; /* 底部大按钮图标宽度 */
            height: 60px; /* 底部大按钮图标高度 */
            object-fit: contain;
        }

        #microphoneButtonText {
            font-size: 14px;
            color: #333;
            font-weight: 500;
        }
    </style>
</head>

<body>
<!-- 摄像头信息区 -->
<div class="camera-info">
    <div class="info-item">
        <span id="title"></span>
    </div>
</div>

<!-- 视频显示区 -->
<div class="video-section">
    <video id="webRtcPlayerBox" class="video-js" poster="static/connecting.gif" data-setup="{}" playsinline
           preload autoplay></video>
</div>

<!-- 功能标签栏 -->
<div class="tab-bar">
    <div class="tab-item active">实时直播</div>
    <!--    <div class="tab-item">录像</div>-->
    <!--    <div class="tab-item">消息</div>-->
</div>

<!-- 操作按钮区 -->
<div class="action-buttons">
    <!--    <div class="button">-->
    <!--        <div class="icon">-->
    <!--            <img src="./static/record.png" alt="Record Icon">-->
    <!--        </div>-->
    <!--        <span>录像</span>-->
    <!--    </div>-->
    <div id="soundButton" class="button">
        <div class="icon">
            <img src="./static/sound.svg" alt="Sound Icon">
        </div>
        <span>声音</span>
    </div>
    <div id="cameraButton" class="button">
        <div class="icon">
            <img src="./static/camera.svg" alt="Photo Icon">
        </div>
        <span>拍照</span>
    </div>
    <!--    <div class="button">-->
    <!--        <div class="icon">-->
    <!--            <img src="./static/alarm.png" alt="Alarm Icon">-->
    <!--        </div>-->
    <!--        <span>报警</span>-->
    <!--    </div>-->
    <!--    <div class="button">-->
    <!--        <div class="icon">-->
    <!--            <img src="./static/light.png" alt="Light Icon">-->
    <!--        </div>-->
    <!--        <span>暖光灯</span>-->
    <!--    </div>-->
</div>

<!-- 底部大按钮 -->
<div class="big-button">
    <div class="big-icon" onclick="broadcastStatusClick()">
        <img id="microphoneButtonImg" src="./static/microphone2.png" alt="Microphone Icon">
    </div>
    <span id="microphoneButtonText">点击通话</span>
</div>
</body>
<script type="text/javascript" src="js/ZLMRTCClient.js"></script>
<script type="text/javascript" src="js/jsonly.js"></script>
<script type="text/javascript" src="js/webview.js"></script>
<script>
    // -2 正在释放资源 -1 默认状态 0 等待接通 1 接通成功


    let broadcastStatus = -1;
    let broadcastRtc = null;
    let webrtcPlayer = null;
    document.addEventListener('DOMContentLoaded', function () {
        /**
         * 获取页面高度 减去上面筛选的高度 再减去下面底部的高度 单位px
         * 返回需要转换为rpx
         */
        const windowHeight = window.innerHeight
        /**
         * h5获取的height是所有元素的height
         * 微信获取的height是不包标题栏的
         * 但是h5的标题高度会在top属性显示  微信为0
         * 使用height - top就是实际页面高度 不用判断环境了
         */
            // 头部区域高度
        const headHeight = 40;
        // 底部区域高度
        const bottomHeight = 30;
        const desiredHeight = windowHeight - headHeight - bottomHeight;

        // Set the calculated height to .card-body
        const cardBody = document.querySelector('.card-body');
        if (cardBody) {
            cardBody.style.height = `${desiredHeight}px`;
        }

        // Optional: Adjust the card-body height on window resize if needed
        window.addEventListener('resize', function () {
            cardBody.style.height = `${desiredHeight}px`;
        });
        document.title = null;
        // 获取当前页面的 URL
        var urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('title')) {
            document.getElementById("title").innerText = urlParams.get('title').trim();
        }
    });
    /**
     * 初始化加载完成 请求父组件调用播放
     */
    console.log("网页加载完成", document);
    document.addEventListener('UniAppJSBridgeReady', function () {
        uni.webView.getEnv(function (res) {
            console.log('当前环境：' + JSON.stringify(res));
        });
        let message = {
            "option": "ready",
        };
        sendMessage(message);
    });
    /**
     * 接收uniapp消息
     * @param arg
     */
    window.getUniAppMessage = (arg) => {
        console.log("网页收到消息", arg);
        let message = jsonly(arg);
        if (message.option == "play") {
            playVideo(message.webrtc);
        } else if (message.option == "broadcastStart") {
            console.log("message.broadcastUrl", message.broadcastUrl);
            startBroadcast(message.broadcastUrl);
        }
    };

    function playVideo(url) {
        webrtcPlayer = new ZLMRTCClient.Endpoint({
            element: document.getElementById('webRtcPlayerBox'),
            debug: true,
            zlmsdpUrl: url,
            simulecast: false,
            useCamera: false,
            audioEnable: true,
            videoEnable: true,
            recvOnly: true,
            usedatachannel: false,
        });

        webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR, (e) => {
            console.error('ICE negotiation error');
            eventCallback("ICE ERROR", "ICE negotiation error");
        });

        webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_REMOTE_STREAMS, (e) => {
            console.log('Playback successful', e.streams);
        });

        webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, (e) => {
            console.error('Offer/Answer exchange failed', e);
            toast("OFFER ANSWER ERROR", "Offer/Answer exchange failed");
            if (e.code === -400 && e.msg === "Stream not found") {
                console.log("Stream not found");
                setTimeout(() => {
                    webrtcPlayer.close();
                    playVideo(url);
                }, 100);
            }
        });

        webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_LOCAL_STREAM, (s) => {
            toast("LOCAL STREAM", "Local stream obtained");
        });
    }

    function pause() {
        if (webrtcPlayer !== null) {
            webrtcPlayer.close();
            webrtcPlayer = null;
        }
    }

    // Cleanup on unload
    window.addEventListener('unload', () => {
        if (webrtcPlayer !== null) {
            webrtcPlayer.close();
        }
    });

    function sendMessage(mes) {
        let message = {
            data: mes
        }
        console.log("网页向uniapp发送消息", message);
        uni.webView.postMessage(message);
    }

    function broadcastStatusClick() {
        console.log("点击语音对讲");
        if (broadcastStatus === -1) {
            console.log("开始语音对讲");
            let message = {
                "option": "broadcast",
            };
            sendMessage(message);
        } else if (broadcastStatus === 1) {
            console.log("关闭语音对讲");
            updateBroadcastStatus(-1);
            broadcastRtc.close()
        }
    }

    function toast(message) {
        console.log("toast", message);
        let messageObj = {
            "option": "toast",
            "message": message
        };
        console.log("网页向uniapp发送弹框消息", messageObj);
        sendMessage(messageObj);
    }

    function startBroadcast(url) {
        console.log("开始语音对讲", url);
        broadcastRtc = new ZLMRTCClient.Endpoint({
            debug: true, // 是否打印日志
            zlmsdpUrl: url, //流地址
            simulecast: false,
            useCamera: false,
            audioEnable: true,
            videoEnable: false,
            recvOnly: false,
        });
        broadcastRtc.on(ZLMRTCClient.Events.WEBRTC_NOT_SUPPORT, (e) => {// 获取到了本地流
            console.log('不支持webrtc', e);
            toast("不支持webrtc");
            updateBroadcastStatus(-1);
        });

        broadcastRtc.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR, (e) => {// ICE 协商出错
            console.error('ICE 协商出错')
            toast("ICE 协商出错");
            updateBroadcastStatus(-1);
        });

        broadcastRtc.on(ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, (e) => {// offer anwser 交换失败
            console.error('offer anwser 交换失败', e)
            toast("offer anwser 交换失败");
            updateBroadcastStatus(-1);
            broadcastRtc.close();
        });
        broadcastRtc.on(ZLMRTCClient.Events.WEBRTC_ON_CONNECTION_STATE_CHANGE, (e) => {// offer anwser 交换失败
            console.log('状态改变', e)
            if (e === "connecting") {
                updateBroadcastStatus(0);
            } else if (e === "connected") {
                updateBroadcastStatus(1);
            } else if (e === "disconnected") {
                updateBroadcastStatus(-1);
            }
        });
        broadcastRtc.on(ZLMRTCClient.Events.CAPTURE_STREAM_FAILED, (e) => {// offer anwser 交换失败
            console.log('捕获流失败', e)
            toast("捕获流失败");
            updateBroadcastStatus(-1);
        });
    }

    function updateBroadcastStatus(newBroadcastStatus) {
        broadcastStatus = newBroadcastStatus;
        if (broadcastStatus === 0) {
            document.getElementById("microphoneButtonImg").src = "./static/microphone3.png";
            document.getElementById("microphoneButtonText").innerText = "等待接通中...";
        } else if (broadcastStatus === 1) {
            document.getElementById("microphoneButtonImg").src = "./static/microphone1.png";
            document.getElementById("microphoneButtonText").innerText = "请说话";
        } else if (broadcastStatus === -1) {
            document.getElementById("microphoneButtonImg").src = "./static/microphone2.png";
            document.getElementById("microphoneButtonText").innerText = "点击通话";
        } else if (broadcastStatus === -2) {
            document.getElementById("microphoneButtonImg").src = "./static/microphone4.png";
            document.getElementById("microphoneButtonText").innerText = "正在释放资源";
        }
    }

    // 新增声音控制功能
    document.getElementById('soundButton').addEventListener('click', function() {
        const video = document.getElementById('webRtcPlayerBox');
        video.muted = !video.muted;
        this.querySelector('img').src = video.muted ? './static/mute.svg' : './static/sound.svg';
    });

    // 新增拍照功能
    document.getElementById('cameraButton').addEventListener('click', function() {
        const video = document.getElementById('webRtcPlayerBox');
        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0);

        const screenshotData = canvas.toDataURL('image/png');
        // 向 UniApp 发送截图数据
        let message = {
            "option": "saveScreenshot",
            "message": screenshotData
        };
        sendMessage(message);
    });
</script>
</html>
